// 2. 引入createSlice 返回reducer
import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

// 1.定义state
interface ProductSearchState {
  data: any;
  loading: boolean; // 请求状态
  error: string | null; // 错误信息
  pagination: any; // 分页信息
}

const defaultState: ProductSearchState = {
  data: [],
  loading: false,
  error: null,
  pagination: {// 初始化要赋值 不然会报错
    currentPage:1,
    pageSize:10,
    totalCount:0,
  },
};

// 4.定义异步函数
export const getProductSearch = createAsyncThunk(
  "productSearch/getProductSearch",
  async (paramaters: {
    keywords: string;
    nextPage: number | string;
    pageSize: number | string;
  }) => {
    let url = `http://123.56.149.216:8080/api/touristRoutes?pageNumber=${paramaters.nextPage}&pageSize=${paramaters.pageSize}`;
    if (paramaters.keywords) {
      url += `&keyword=${paramaters.keywords}`;
    }
    const res = await axios.get(url);
    console.log(res, "res");

    return {
      data: res.data,
      pagination:  JSON.parse(res.headers["x-pagination"])
    };
  }
);

// 3.p抛出slice
export const productSearchSlice = createSlice({
  name: "productSearch",
  initialState: defaultState,
  reducers: {},
  [getProductSearch.pending.type]: (state) => {
    // return { ...state, loading: true };// !return 这是react的写法 state是immutable不可以修改的
    state.loading = true; // immer框架 内部的produce实现返回了一个新的object
  },
  [getProductSearch.fulfilled.type]: (state, action) => {
    state.loading = false;
    state.data = action.payload.data; // 更新状态 getProductSearch返回
    state.pagination = action.payload.pagination;
    state.error = null;
  },
  [getProductSearch.rejected.type]: (state, action: PayloadAction<string | null>) => {
    state.loading = false;
    state.error = action.payload;
  },
});
